//
//  BMPreferences.m
//  snomPhone
//
//  Created by Daniel Hazelbaker on 11/4/08.
//  Copyright 2008 Blue Box Moon. All rights reserved.
//

#import "BMPreferences.h"
#import "DeepCopy.h"


@implementation BMPreferences


//
// Create a new autoreleased preferences object.
//
+ (BMPreferences *)preferences
{
    return [[[self alloc] init] autorelease];
}


//
// Create a new autoreleased preferences object for the given identifier.
//
+ (BMPreferences *)preferencesWithIdentifier:(NSString *)identifier
{
    return [[[self alloc] initWithIdentifier:identifier] autorelease];
}


//
// Initialize this object with the main bundle identifier.
//
- (id)init
{
    return [self initWithIdentifier:[[NSBundle bundleForClass:[self class]] bundleIdentifier]];
}


//
// Initialize this object with the given identifier.
//
- (id)initWithIdentifier:(NSString *)inIdentifier
{
    if ([super init] == nil)
	return nil;

    identifier = [inIdentifier copy];

    return self;
}


//
// Free memory used by this preferences object.
//
- (void)dealloc
{
    [self synchronize];

    if (identifier != nil) {
	[identifier autorelease];
	identifier = nil;
    }

    [super dealloc];
}


//
// Determines if the key is forced via MCX.
//
- (BOOL)valueIsForcedForKey:(NSString *)key
{
    return CFPreferencesAppValueIsForced((CFStringRef)key, (CFStringRef)identifier);
}


//
// Save the preferences to disk.
//
- (void)synchronize
{
    CFPreferencesAppSynchronize((CFStringRef)identifier);
}


//
// Set a key/value in the preferences.
//
- (void)setValue:(id)value forKey:(NSString *)key
{
    CFPreferencesSetAppValue((CFPropertyListRef)key, value, (CFStringRef)identifier);
}


//
// Set a key/value in the preferences for the given key path.
//
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath
{
    if ([keyPath rangeOfString:@"."].location == NSNotFound)
	[self setValue:value forKey:keyPath];
    else
	[NSException raise:NSInvalidArgumentException format:@"Key paths (%@) are not supported in BMPreferences.", keyPath];
}


//
// Retrieve a value for the given key in the preferences.
//
- (id)valueForKey:(NSString *)key
{
    return [(id)CFPreferencesCopyAppValue((CFStringRef)key, (CFStringRef)identifier) autorelease];
}


//
// Retrieve a value for the given key path in the preferences.
//
- (id)valueForKeyPath:(NSString *)keyPath
{
    if ([keyPath rangeOfString:@"."].location == NSNotFound)
	return [self valueForKey:keyPath];

    [NSException raise:NSInvalidArgumentException format:@"Key paths (%@) are not supported in BMPreferences.", keyPath];
    return nil;
}


@end
